package cn.qvtu.web.controller;

import cn.qvtu.web.domain.User;
import cn.qvtu.web.service.IUserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
@Slf4j
public class LoginController {

    @Autowired
    private IUserService userService;

    @GetMapping("/login")
    public String login(){
        return "client/login";
    }

    @PostMapping("/login")
    public String formLogin(String username, String password, HttpServletRequest request) {
        if(StringUtils.isBlank(username) || StringUtils.isBlank(password)){
            return "redirect:/login?error";
        }
        QueryWrapper<User> query = new QueryWrapper<>();
        query.eq("username",username);
        User user = userService.getOne(query);
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String encode = encoder.encode(password);
        if(!encoder.matches(password,user.getPassword())){
            return "redirect:/login?error";
        }
        request.getSession().setAttribute("loginUser",user);
        log.info("登录成功:"+username);
        return "redirect:/";
    }

    @RequestMapping ("/logout")
    public String logout(HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.invalidate();
        log.info("注销成功:");
        return "redirect:/";
    }
    
}
